import numpy as np
import itertools
def find_concepts(table):
    concepts = []
    # 遍历所有可能的属性集合
    for attr_indices in itertools.product([0, 1], repeat=table.shape[1]):
        if sum(attr_indices) > 0:  # 忽略全为0的情况
            attr_set = set(np.where(attr_indices)[0])
            # 找出具有这些属性的所有对象
            matching_objects = [i for i, row in enumerate(table) if all(row[attr] == 1 for attr in attr_set)]
            if matching_objects:  # 如果有对象匹配，则这是一个概念
                concepts.append((set(matching_objects), attr_set))
    return concepts

# 示例：生成一个有10个对象，5个属性的零一表
objects_count = 10
attributes_count = 5
np.random.seed(0)  # 为了可重复性，设置随机种子
table = np.random.randint(2, size=(objects_count, attributes_count))
'''
# 找到表中的概念
concepts = find_concepts(table)

# 打印结果
print("生成的零一表：")
print(table)
print("\n找到的概念：")
for concept in concepts:
    object_labels = [f'o{i+1}' for i in concept[0]]
    attribute_labels = [f'a{j+1}' for j in concept[1]]
    print(f"对象集合: {object_labels}, 属性集合: {attribute_labels}")'''


def generate_concept_lattice_table(objects_count, attributes_count, concepts_count):
    while True:
        # 生成随机的零一表
        table = np.random.randint(2, size=(objects_count, attributes_count))
        
        # 转换为概念格的上下文格式
#         context = Context(table, row_labels=[f'o{i+1}' for i in range(objects_count)], col_labels=[f'a{i+1}' for i in range(attributes_count)])
        #
        # 生成概念格
#         lattice = context.lattice()
        
        # 检查概念个数是否满足要求
        if len(find_concepts(table)) >= concepts_count:
            return table, find_concepts(table)

# 示例：生成一个有7个对象，5个属性，至少15个概念的表
objects_count = 7
attributes_count = 5
concepts_count = 15

table, n = generate_concept_lattice_table(objects_count, attributes_count, concepts_count)
print("生成的零一表：")
print(table)

# print("\n生成的概念格：")
# for concept in lattice:
#     print(f"对象集合: {concept['intent']}, 属性集合: {concept['extent']}")

print(f"\n总共生成了 {len(n)} 个概念。")
print(n)